/**
 * @overview socket事件处理类
 */
import { useBusinessStore,  } from '@/store'
const store = useBusinessStore()
/** debounce 目的是后台一次性推多条警情， */
const debouncedFn = useDebounceFn(() => { }, 1000)
// 连接次数
let count = 0
class useSocket {
  url: any
  static ws: any
  constructor() {
    this.initSocket()
  }
  initSocket(url?: string) {
    const _this = this
    const ws_url = window.ApiDev.socketUrl + `/${Math.ceil(Math.random() * 100000 + 100000)}?zzzd=5`
    useSocket.ws = new WebSocket(ws_url)
    console.log('websocket正在连接');
    useSocket.ws.onopen = function (e: any) {
      count = 0
      console.log('socket连接成功')
    }
    useSocket.ws.onerror = function (e: any) {
      console.log('socket连接失败次数', count)
      console.log('socket连接失败', e)
      count++

      if (count === 100) {
        return 
      }
      setTimeout(() => {
        _this.initSocket(url)
      }, 30000);
    }
    useSocket.ws.onmessage = function (e: { data: string }) {
      try {
        const msgObj = JSON.parse(e.data) as any
        if (typeof _this[(msgObj as any).event] === 'function') {
          _this[msgObj.event](msgObj.data)
          console.log('webSocket事件:',msgObj.event);
        }
      } catch (e) {
        console.error('chemical_socket接收消息出错，', e)
      }
    }
    // 连接关闭
    useSocket.ws.onclose = function (e: any) {
      console.log("socket被关闭");
      count++
      if (count == 100) {
        return 
      }
      setTimeout(() => {
        _this.initSocket(url)
      }, 30000);
    }
  }
  reConnect(url: string) {
    useSocket.ws.close()
    this.initSocket(url)
  }

 
}
export { useSocket }
